package megrez.bussiness.schedule.service;

import java.util.Optional;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import lombok.RequiredArgsConstructor;
import megrez.bussiness.schedule.entity.Job;
import megrez.bussiness.schedule.entity.Job.State;
import megrez.bussiness.schedule.entity.JobLog;
import megrez.bussiness.schedule.entity.JobLog.Level;
import megrez.bussiness.schedule.repository.JobLogRepository;
import megrez.bussiness.schedule.repository.JobRepository;
import megrez.common.util.EntityMissingException;

/**
 * 任务信息服务
 *  
 * @author Lucky Yang
 * @since 0.0.1
 */
@Service
@RequiredArgsConstructor
public class JobService {
    private final JobRepository jobRepository;
    private final JobLogRepository jobLogRepository;

    public Job findJobById(Long jobId) {
        return jobRepository.findById(jobId).orElseThrow(EntityMissingException::new);
    }

    @Transactional(rollbackFor = Exception.class)
    public Job saveJob(Job job) {
        Job entity = Optional.ofNullable(job.getId()).map(id -> {
            Job persistence = findJobById(id);
            persistence.copy(job);
            return persistence;
        }).orElse(job);

        return jobRepository.save(entity);
    }

    @Transactional(rollbackFor = Exception.class)
    public Job updateJobState(Long jobId, State state) {
        Job job = this.findJobById(jobId);
        job.setState(state);
        return jobRepository.save(job);
    }

    @Transactional(rollbackFor = Exception.class)
    public JobLog createLog(Long jobId, Level level, String message) {
        return createLog(jobId, level, message, null);
    }

    @Transactional(rollbackFor = Exception.class)
    public JobLog createLog(Long jobId, Level level, String message, Long costTime) {
        Job job = this.findJobById(jobId);
        JobLog entity = new JobLog(job, level, message, costTime);
        return jobLogRepository.save(entity);
    }
}
